/******************************************************************************
This file is part of AppKit.
Project: appkit
Author : FergusZeng
Email  : cblock@126.com
git	   : https://gitee.com/newgolo/appkit.git
*******************************************************************************
MIT License

Copyright (c) 2022 cblock@126.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/
#include "appkit/tracer.h"

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <syslog.h>
#include <unistd.h>

#include <iostream>
#include <thread>

#include "appkit/socket.h"
#include "appkit/strutil.h"
#include "appkit/system.h"
#include "appkit/thread.h"

#if USE_ROS_LOG
#include <ros/console.h>
#include <ros/ros.h>
#endif

namespace appkit {
/* 打印长度最大为4096Bytes,超出后显示省略号 */
static const int kTraceMaxLength = 4096;
TraceDuration::TraceDuration(const std::string& tag, uint32 msDuration)
    : m_tag(tag), m_duration(msDuration) {
    m_startTime = Time::fromMono();
}

TraceDuration::~TraceDuration() {
    auto diff = Time::fromMono() - m_startTime;
    if (diff.toMicroSec() / 1000 >= m_duration) {
        TRACE_I("[%s] trace duration: %s s", m_tag.data(),
                diff.toString().data());
    }
}

Tracer::Tracer() { setvbuf(stdout, nullptr, _IONBF, BUFSIZ); }
Tracer::~Tracer() {
    m_isStart.store(false);
    if (m_future.valid()) {
        m_future.wait();
    }
    sinkMsg();  // 打印最后的消息
}

void Tracer::print(int level, const char* format, ...) {
    if (level < m_level) { /* 打印级别大于等于当前级别的才允许打印 */
        return;
    }
    auto printBuf = std::make_unique<char[]>(kTraceMaxLength);
    char* buf = printBuf.get();
    va_list argp;
    va_start(argp, format);
    int size = kTraceMaxLength - 1;
    size = vsnprintf(buf, size, format, argp);
    va_end(argp);
    if (size > 0) {
        if (size >= kTraceMaxLength) { /* 超过长度了 */
            buf[kTraceMaxLength - 4] = '.';
            buf[kTraceMaxLength - 3] = '.';
            buf[kTraceMaxLength - 2] = '.';
            buf[kTraceMaxLength - 1] = 0;
            size = kTraceMaxLength;
        }
        std::string out(buf, size);
        std::lock_guard<std::mutex> lock(m_logMutex);
        m_logVect.push_back(out);
    }
}

Tracer& Tracer::setLevel(int level) {
    m_level = CLIP(TRACE_LEVEL_MIN, level, TRACE_LEVEL_MAX);
    for (auto& sink : m_sinkVect) {
        sink->onLevelChanged(m_level);
    }
    return *this;
}

int Tracer::getLevel() { return m_level; }

Tracer& Tracer::addSink(std::shared_ptr<TracerSink> sink) {
    if (m_isStart.load()) {
        return *this;
    }
    // 只允许加入一个STDSink
    if (sink->__CLASS_NAME() == "STDSink") {
        if (m_hasSTDSink) {
            sink->onLevelChanged(m_level);
            return *this;
        } else {
            m_hasSTDSink = true;
        }
    }
    sink->onLevelChanged(m_level);
    std::lock_guard<std::mutex> lock(m_sinkMutex);
    m_sinkVect.push_back(std::move(sink));
    return *this;
}

void Tracer::sinkMsg() {
    std::vector<std::string> logVect;
    {
        std::lock_guard<std::mutex> lock(m_logMutex);
        if (m_logVect.empty()) {
            return;
        }
        std::swap(m_logVect, logVect);
    }
    for (auto log : logVect) {
        int uid = 0;
        switch (log[1]) {
            case 'D':
                uid = TRACE_LEVEL_DBG;
                break;
            case 'I':
                uid = TRACE_LEVEL_INFO;
                break;
            case 'W':
                uid = TRACE_LEVEL_WARN;
                break;
            case 'E':
                uid = TRACE_LEVEL_ERR;
                break;
            case 'F':
                uid = TRACE_LEVEL_FATAL;
                break;
            case 'C':
                uid = TRACE_LEVEL_INFO;
                log = log.substr(3);
                break;
            case 'L': {
                uid = std::stoi(StrUtil::findString(log, "<", ">").substr(2));
                if (uid <= TRACE_LEVEL_MAX) {
                    continue;
                }
                break;
            }
            default:
                continue;
        }
        std::lock_guard<std::mutex> lock(m_sinkMutex);
        for (auto& sink : m_sinkVect) {
            sink->sink(uid, log);
        }
    }
}

void Tracer::start() {
    if (!m_isStart.load()) {
        m_future = std::async(std::launch::async, [&]() {
            m_isStart.store(true);
            Rate rate(100.0f);
            while (m_isStart.load()) {
                sinkMsg();
                rate.sleep();
            }
            m_isStart.store(false);
        });
    }
}

void Tracer::flush() {
    for (auto& sink : m_sinkVect) {
        sink->onFlushed();
    }
}

STDSink::STDSink() {}
STDSink::~STDSink() {}
void STDSink::sink(int uid, const std::string& msg) {
    if (uid < TRACE_LEVEL_MIN || uid > TRACE_LEVEL_MAX) {
        return;
    }
    std::string color = "";
    switch (uid) {
        case TRACE_LEVEL_DBG:
            color = "\033[36m\033[1m";
            break;
        case TRACE_LEVEL_WARN:
            color = "\033[33m\033[1m";
            break;
        case TRACE_LEVEL_ERR:
            color = "\033[31m\033[1m";
            break;
        case TRACE_LEVEL_INFO:
            std::cout << msg << std::endl;
            return;
        default:
            return;
    }
    std::cout << color << msg << "\033[0m" << std::endl;
}

SyslogSink::SyslogSink() {}
SyslogSink::~SyslogSink() {}
void SyslogSink::sink(int uid, const std::string& msg) {
    if (uid < TRACE_LEVEL_MIN || uid > TRACE_LEVEL_MAX) {
        return;
    }
    int priority = LOG_DEBUG;
    switch (uid) {
        case TRACE_LEVEL_WARN:
            priority = LOG_WARNING;
            break;
        case TRACE_LEVEL_ERR:
            priority = LOG_ERR;
            break;
        case TRACE_LEVEL_INFO:
            priority = LOG_INFO;
            break;
        default:
            break;
    }
    syslog(priority, "%s", CSTR(msg));
}

#if USE_ROS_LOG
ROSSink::ROSSink() {}
ROSSink::~ROSSink() {}
void ROSSink::onLevelChanged(int level) {
    ros::console::levels::Level lvl = ros::console::levels::Info;
    switch (level) {
        case TRACE_LEVEL_DBG:
            lvl = ros::console::levels::Debug;
            break;
        case TRACE_LEVEL_WARN:
            lvl = ros::console::levels::Warn;
            break;
        case TRACE_LEVEL_ERR:
            lvl = ros::console::levels::Error;
            break;
        case TRACE_LEVEL_INFO:
            lvl = ros::console::levels::Info;
            break;
        default:
            break;
    }
    if (ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, lvl)) {
        ros::console::notifyLoggerLevelsChanged();
    }
}

void ROSSink::sink(int uid, const std::string& msg) {
    switch (uid) {
        case TRACE_LEVEL_DBG:
            ROS_DEBUG_STREAM(msg);
            break;
        case TRACE_LEVEL_ERR:
            ROS_ERROR_STREAM(msg);
            break;
        case TRACE_LEVEL_INFO:
            ROS_INFO_STREAM(msg);
            break;
        case TRACE_LEVEL_WARN:
            ROS_WARN_STREAM(msg);
            break;
        default:
            // ROS_FATAL_STREAM(msg);
            break;
    }
}
#endif
}  // namespace appkit
